/*
 * Copyright (c) 2003, 2004 Ulrich Hilger, http://dev.uhilger.de, all rights reserved.
 *
 * Published under the terms and conditions of the Apache License 2.0,
 * see http://www.apache.org/licenses/LICENSE-2.0
 */

package de.uhilger.app;

import java.io.*;
import java.util.ArrayList;
import javax.swing.JTextArea;

/**
 * a custom <code>OutputStream</code> that allows to optionally
 * echo output to a JTextArea.
 *
 * <p>In this application this stream is used to log messages to a JTextArea.
 * For this purpose the application logger is extended by an additional
 * <code>StreamHandler</code> which allows the logger to log to an instance of this
 * class. Upon initialization of the application, a JTextArea is registered to
 * this <code>TextComponentStream</code> so that all logging to this stream finally
 * is shown in the JTextArea.</p>
 *
 * @author Ulrich Hilger, <a href="http://dev.uhilger.de" target="_blank">http://dev.uhilger.de</a>
 * @author Published under the terms and conditions of
 * the <a href="http://www.apache.org/licenses/LICENSE-2.0" target="_blank">Apache License 2.0</a>
 *
 * @version 1, July 11, 2004
 */

public class TextComponentStream extends OutputStream {

  /**
   * constructor
   */
  public TextComponentStream() {
    byteList = new ArrayList();
  }

  /**
   * set the text component to which output shall be echoed
   * @param ta JTextArea  the component to echo to
   */
  public void setTextComponent(JTextArea ta) {
    this.ta = ta;
  }

  /**
   * write to an array list, i.e. buffer output until flush() is called which
   * is when the buffered output is transferred to the text component and the
   * buffer is cleared
   * @param b int
   */
  public void write(int b) {
    byteList.add(new Byte( (byte) b));
  }

  /**
   * empty the output buffer and transfer buffered output to
   * a text component (if one is registered with this stream)
   */
  public void flush() {
    byte[] bytes = new byte[byteList.size()];
    for (int i = 0; i < bytes.length; i++) {
      bytes[i] = ( (Byte) byteList.get(i)).byteValue();
    }
    byteList.clear();
    if(ta != null) {
      ta.append(new String(bytes));
      ta.setCaretPosition(ta.getText().length());
    }
  }

  /** the output buffer */
  private ArrayList byteList;

  /** the text component to echo output to */
  private JTextArea ta;
}
